package lt.vin.currency.server.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;

import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

import lt.vin.currency.client.service.CurrencyService;
import lt.vin.currency.server.SourceReader;
import lt.vin.currency.server.dao.CurrencyDao;
import lt.vin.currency.shared.Source;
import lt.vin.currency.shared.TestResult;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * The server side implementation of the RPC service.
 */
@Singleton
@SuppressWarnings("serial")
public class CurrencyServiceImpl extends RemoteServiceServlet implements CurrencyService {

	@Inject CurrencyDao currencyDao;

	@Override
	public List<Source> getSources() {
		return currencyDao.getSources();
	}

	@Override
	public TestResult testSource(Source source) {
		SourceReader reader = new SourceReader(source);
		
		String rawData;
		try {
			rawData = reader.getRawData();
		} catch (MalformedURLException e) {
			rawData = formatException(e);
		} catch (IOException e) {
			rawData = formatException(e);
		} catch (TransformerException e) {
			rawData = formatException(e);
		}
		
		String data;
		try {
			data = reader.getDataXml();
		} catch (TransformerConfigurationException e) {
			data = formatException(e);
		} catch (MalformedURLException e) {
			data = formatException(e);
		} catch (TransformerException e) {
			data = formatException(e);
		} catch (IOException e) {
			data = formatException(e);
		}
		
		return new TestResult(rawData, data);
	}
	
	private String formatException(Exception e) {
		StringWriter writer = new StringWriter();
		
		e.printStackTrace(new PrintWriter(writer));
		
		return writer.toString();
	}

	/* (non-Javadoc)
	 * @see com.gcgt.client.GreetingService#saveSource(lt.vin.currency.shared.Source)
	 */
	@Override
	public void saveSource(Source source) {
		currencyDao.save(source);		
	}

	@Override
	public List<String> getAvailableCurrencies() {
		return Arrays.asList(new String[] {"EUR", "USD", "GBP"});
	}
	
	
}
